package com.medical.doctor.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.common.utils.PageUtils;
import com.medical.common.utils.Query;

import com.medical.doctor.dao.AddressDao;
import com.medical.doctor.entity.AddressEntity;
import com.medical.doctor.service.AddressService;


@Service("addressService")
public class AddressServiceImpl extends ServiceImpl<AddressDao, AddressEntity> implements AddressService {

    @Autowired
    private AddressDao addressDao;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AddressEntity> page = this.page(
                new Query<AddressEntity>().getPage(params),
                new QueryWrapper<AddressEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<AddressEntity> tree() {
        List<AddressEntity> address = (List<AddressEntity>) redisTemplate.boundHashOps("addresslist").get("tree");
        if(address==null){
            //先查到所有的类型
            List<AddressEntity> addressEntities = baseMapper.selectList(null);
            for (AddressEntity addressEntity : addressEntities) {
                //所有的一级分类
                List<AddressEntity> pid = baseMapper.selectList(new QueryWrapper<AddressEntity>().eq("aid", 0));
                if(pid!=null && pid.size()>0){
                    for (AddressEntity entity : pid) {
                        //查询所有二级分类
                        List<AddressEntity> pid1 = baseMapper.selectList(new QueryWrapper<AddressEntity>().eq("aid", entity.getAddressId()));
                        if(pid1!=null && pid1.size()>0){
                            //查询所有的三级分类
                            for (AddressEntity addressEntity1 : pid1) {
                                List<AddressEntity> pid2 = baseMapper.selectList(new QueryWrapper<AddressEntity>().eq("aid", addressEntity1.getAddressId()));
                                if(pid2!=null && pid2.size()>0){
                                    addressEntity1.setChildren(pid2);
                                }

                            }
                            entity.setChildren(pid1);
                        }
                    }
                    redisTemplate.boundHashOps("address").put("tree",pid);
                }
                return pid;
            }

        }
        return address;
    }

}